// import * as im from "../ymVoice/ymMgr";

class multGame extends eui.Component {
	private yaogan: roleControl;
	private camera: any;
	/**四号道具 */
	private daotime = Date.now();
	private rr = 0;
	private background: eui.Group = new eui.Group();

	private brorder: eui.Group = new eui.Group();
	/**玩家类型 */
	private clothes_List = ["lv", "huang", "qing"];
	//保存玩家的位置
	public myControlPoint = {
		x: 0,
		y: 0
	};
	//用于手柄部分
	public handle: eui.Image = new eui.Image();//小球
	private circle: eui.Image = new eui.Image();//圈
	private circle_position = { "x": 100, "y": gameGlobal.global.screenHeight - 100 };//圈中心点的位置
	private handle_position = { "x": 100, "y": gameGlobal.global.screenHeight - 100 };//小球中心店的位置
	private touchID: any = null;//触摸id
	private circle_radius: number = 0;
	private handle_radius: number = 0;
	private jiaodu: number = 0;//返回角度
	private container: any;
	public gameMapss: any;
	public tmpPoint: egret.Point;
	/**背景音乐 */
	private bgSound: soundMgr = new soundMgr();

	public constructor() {
		super();
		this.skinName = "resource/assets/skins/gameMapSkin.exml";
		this.init();
		this.once(egret.Event.ADDED_TO_STAGE, this.initialize, this);
		this.tmpPoint = egret.Point.create(0, 0);
	}
	/**初始化 */
	private initialize() {
		this.yaoganInit();
		this.parent.addChild(this.UiLayer);
		this.UiLayer.addChild(this.playerPanel);
		//his.UiLayer.addChild(this.userDied);
		this.UiLayer.addChild(this.GameOver);
		this.playerPanel.startRoomTimer();
		this.changeVisibility(DataProl.gameSceneScal);
	}
	/**相关数据 */
	private con = gameGlobal;
	private config = this.con.global;//account
	/**玩家信息 */
	public player = {
		id: DataProl.account,
		x: this.config.screenWidth / 2,
		y: this.config.screenHeight / 2,
		type: Math.round(Math.random() * 2 + 0),
		screenWidth: this.config.screenWidth,
		screenHeight: this.config.screenHeight,
		target: { x: this.config.screenWidth / 2, y: this.config.screenHeight / 2 },
		name: gameGlobal.global.playerName,
		hue: null,
		massTotal: null,
		cells: null,
		xoffset: -0,
		yoffset: -0,
	};

	//显示玩家的青蛙
	private myUser = { targetx: 0, targety: 0, userSprit: null };


	/**装饰品 */
	private decoration_List = ["lowpoly", "food"];


	/**线层*/
	private tongueLayer: egret.Sprite = new egret.Sprite();

	/**道具层 */
	private propLayer: egret.Sprite = new egret.Sprite();
	/**UI层 */
	private UiLayer: eui.Component = new eui.Component();
	/**游戏结束*/
	private GameOver: GameOver = new GameOver();
	/**玩家死亡 */

	//private userDied: playerDied = new playerDied();

	/**玩家控制面板 */
	private playerPanel: playerPanel = new playerPanel(this);

	/**；存房间玩家/青蛙 动画的容器 */
	private gameFrog = new egret.DisplayObjectContainer();
	/**青蛙管理 */
	private m_createAllFrogs = new frogMgr(this);
	/**房间里所有的线 */
	public roomAllTongue: egret.Sprite = new egret.Sprite();

	public tongueManager: tongueMgr = new tongueMgr(this.roomAllTongue, this.m_createAllFrogs);

	private game_Timer: egret.Timer;

	/**用于存储玩家是否死亡 控制是否接受服务器消息 */
	public isUserDied = false;

	/**道具管理 */
	private m_propMg: propMgr = new propMgr(this.propLayer);
	/**用来保存移动的数据 */
	private m_shadowFrog;
	private init() {
		resManager.getInstance().loadRes();
		console.log("init");
		this.resetShadowForgStates();
		this.startYMVoice();
		this.playBGMusic();
		webNetworkMananger.getInstance().gameSceneRec = this;
		this.m_createAllFrogs.createAllNetFrogs();
		let shadowFrog = this.m_createAllFrogs.findFrogById(DataProl.shadowFrogId);
		if (shadowFrog != null) {

			shadowFrog.reset();
		}

		this.m_shadowFrog = this.m_createAllFrogs.getOneFrog();
		this.m_shadowFrog.born(DataProl.shadowFrogId, "影子", 0, 0, 1, 1, null);

		if (serverConfig.config.shadowFrog) {
			this.m_shadowFrog.visble = true;
		}

		else {
			this.m_shadowFrog.visble = false;
		}
		this.mapInit();
		this.setChildIndex(this.brorder, this.numChildren);
		this.cameraInit();
		this.creatMyFog();
		//this.userDied.visible = false;
		this.GameOver.visible = false;
		this.BeginTimes();
		/**如果是好友模式，局数++ */
		if (DataProl.loginType != 0) {
			DataProl.invoteFriends++;
		}
		DataProl.allPropData = null;
	}

	/**改变游戏内可见范围大小
    * vis: 屏幕缩放比例
    */
	public changeVisibility(vis) {

		egret.MainContext.instance.stage.setContentSize(gameGlobal.global.screenWidth * vis, gameGlobal.global.screenHeight * vis);
		//this.yaogan.changeVis(vis);
		//this.camera.changeVis(vis);
		this.playerPanel.changeVis(vis);
		this.GameOver.changeVis(vis);
		//this.userDied.changeVis(vis);
	}

	/**
	 * 接入游密语音
	 */
	private startYMVoice() {
		//实例化游密语音
		// let ym = new ymMgr();
		// this.addChild(ym);
		// ym.init();
	}
	/**
	 * 播放背景音乐
	 */
	private playBGMusic() {
		this.bgSound.closeSound();
		this.bgSound.playerSound("resource/assets/sound/game.wav", 0);
	}

	/**
	 * 摄像机初始化
	 */
	private cameraInit() {
		var cameraRect: egret.Rectangle = new egret.Rectangle(0, 0, gameGlobal.global.screenWidth * DataProl.gameSceneScal, gameGlobal.global.screenHeight * DataProl.gameSceneScal);
		this.camera = new control.Camera2D(this, cameraRect);
		// this.camera.addLayer(this.playerPanel);
		// this.camera.addLayer(this.GameOver);
		// this.camera.addLayer(this.yaogan);
		// this.camera.addLayer(this.userDied);
		//this.addEventListener(egret.Event.ENTER_FRAME, this.onLoop, this);
	}
	private onLoop(e: egret.Event): void {
		//this.camera.move();
	}
	/**地图初始化 */
	private mapInit() {
		//this.drawBackground();
		//this.drawHexagon();
		//this.creatMapLine();
		/*房间的线 */
		this.addChild(this.roomAllTongue);
		/**房间内的道具 */
		this.addChild(this.propLayer);
		/**房间内的青蛙 */
		this.addChild(this.gameFrog);
	}



	public gameOverDis(data) {
		/**游戏结束关闭玩家死亡界面*/
		//this.userDied.GameOverDis();
		this.GameOver.visible = true;
		this.GameOver.showTops(data);
	}

	/**显示服务器错误信息*/
	public displayErrorMessage(data) {
		console.log(data);
		//this.playerPanel.displayErrorMessage(data);
	}
	private game_Loop_tmp_point = new egret.Point(0, 0);

	/**游戏更新 */
	private game_Loop() {
		this.yaogan.sendPosition();
		this.m_createAllFrogs.updateVeer();
		this.playerPanel.show_frame_number();
		//处理服务器道具信息
		if (DataProl.allPropData != null) {
			this.m_propMg.propsUpdata(DataProl.allPropData);
			//console.log(this.propLayer)
			//DataProl.allPropData = null;
		}
		this.visualChange();
		this.camera.move();
		this.check_can_breakLine();
		/**影子青蛙 */
		//	let shadowFrog = this.m_createAllFrogs.findFrogById(DataProl.shadowFrogId);
		if (this.m_shadowFrog != null) {

			if (this.yaogan.pos.x == 0 && this.yaogan.pos.y == 0)
				return;
			this.game_Loop_tmp_point.setTo(this.yaogan.pos.x, this.yaogan.pos.y);
			this.game_Loop_tmp_point.normalize(this.m_shadowFrog.speed);
			this.game_Loop_tmp_point.setTo(Math.floor(this.game_Loop_tmp_point.x), Math.floor(this.game_Loop_tmp_point.y));
			this.game_Loop_tmp_point.x = Math.floor(this.game_Loop_tmp_point.x * 10) * 0.1;
			this.game_Loop_tmp_point.y = Math.floor(this.game_Loop_tmp_point.y * 10) * 0.1;


			/**影子青蛙移动 */
			//	this.m_shadowFrog .setTargetPoint(this.game_Loop_tmp_point);
			this.m_shadowFrog.frogVeer();
			this.m_shadowFrog.shadowFrogMoveto(this.game_Loop_tmp_point);
		}

	}

	public resetShadowForgStates() {
		serverConfig.config.shadowFrog = 1;
	}

	/**视野变化 */
	public visualChange() {
		let myFrog = this.m_createAllFrogs.findFrogById(DataProl.account);
		if (myFrog != null)
			this.scaleX = this.scaleY = 1 - myFrog.frogLineLength / 45000;
	}
	/**玩家伸舌 */
	public playerLoll() {
		this.m_createAllFrogs.frogLoll();
	}
	/**处理玩家伸舌 */
	public dellPlayerShoot(user) {
		if (user.account != DataProl.account) {
			//吐舌广播
			this.m_createAllFrogs.showShoot(user);
			//动画广播
			this.m_createAllFrogs.tweenshoot(user);
		}
		else {
			this.m_createAllFrogs.tweenshoot(user);
		}
	}
	/**检测是否可以断线 */
	private check_can_breakLine() {
		if (this.m_createAllFrogs.checkPlayerIsLine()) {
			this.playerPanel.coolDown.visible = false;
			this.playerPanel.breakLine.visible = true;
			this.playerPanel.ligature.visible = false;
		} else {
			this.playerPanel.breakLine.visible = false;
			this.playerPanel.ligature.visible = true;
		}
	}
	/**发送心跳 */
	public sendHeart() {
		let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
		m_AwesomeMessage.meesageId = 100;
		var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
		var byte2: egret.ByteArray = new egret.ByteArray(buffer);
		webNetworkMananger.getInstance().SendBitMeesage(byte2);
	}
	/**定时器*/
	private BeginTimes() {
		this.game_Timer = new egret.Timer(1000 / 60, -1);
		this.game_Timer.addEventListener(egret.TimerEvent.TIMER, this.game_Loop, this);
		this.game_Timer.start();
	}

	/**处理服务器发来的消息 */
	public handleInformationByServer(playerdata: any) {
		if (!webNetworkMananger.isServerMove) {
			return;
		}
		//整理玩家的位置/装扮/状态/道具开始时间
		for (var i = 0; i < playerdata.userData.length; i++) {
			playerdata.userData[i].x = playerdata.userData[i].x * 0.1;
			playerdata.userData[i].y = playerdata.userData[i].y * 0.1;
			playerdata.userData[i].Dressup.decorateId -= 1;
			playerdata.userData[i].Dressup.trailingId -= 1;
			playerdata.userData[i].propStates.getPropType -= 1;
			playerdata.userData[i].propStates.PropStartTime -= 1;
		}
		//整理线的信息
		for (var i = 0; i < playerdata.lineList.length; i++) {
			playerdata.lineList[i].uop.x = playerdata.lineList[i].uop.x * 0.1;
			playerdata.lineList[i].utp.x = playerdata.lineList[i].utp.x * 0.1;
			playerdata.lineList[i].uop.y = playerdata.lineList[i].uop.y * 0.1;
			playerdata.lineList[i].utp.y = playerdata.lineList[i].utp.y * 0.1;
		}
		//	playerdata.userData[i].timeStamp = playerdata.timeStamp;

		//	this.sendHeart();
		/**线的数据 */
		var lineData = playerdata.lineList;
		/**玩家数据 */
		var userData = playerdata.userData;
		/**判断是否复活 */
		if (this.isUserDied) {
			let isResurgence: boolean = this.checkUserResurgence(userData)
			if (!isResurgence) {
				return;
			} else {
				this.isUserDied = false;
			}
		}
		if (userData != null) {
			// /**玩家排行榜 */
			// this.playerPanel.disposAllUser(userData);
			//处理青蛙的移动
			//	console.log("ttttt"+userData[0].x);
			this.m_createAllFrogs.disposeRoomUserMessage(userData);
		}
		if (lineData != null) {
			/**处理玩家身上的线 */
			this.tongueManager.gameTongueDataUpdata(userData, lineData);
			if (lineData.length > 0) {
				this.checkUserLineNumber(lineData);
			}
		}

	}
	/**检测玩家连线数量 */
	public checkUserLineNumber(lineData) {
		for (let i = 0; i < lineData.length; i++) {
			if (lineData[i].userOneId == DataProl.account) {
				if (DataProl.connectionNumber.length > 0) {
					for (let j = 0; j < DataProl.connectionNumber.length; j++) {
						if (DataProl.connectionNumber[j] == lineData[i].userTwoId) {
							return;
						}
					}
					DataProl.connectionNumber.push(lineData[i].userTwoId);
				} else {
					DataProl.connectionNumber.push(lineData[i].userTwoId);
				}

			} else if (lineData[i].userTwoId == DataProl.account) {
				if (DataProl.connectionNumber.length > 0) {
					for (let j = 0; j < DataProl.connectionNumber.length; j++) {
						if (DataProl.connectionNumber[j] == lineData[i].userOneId) {
							return;
						}
					}
					DataProl.connectionNumber.push(lineData[i].userOneId);
				} else {
					DataProl.connectionNumber.push(lineData[i].userOneId);
				}
			}
		}
	}

	/**处理青蛙断线反作用力 */
	public disposeCounterforce(data) {
		if (data.shootObjStates == null && data.shootObjStates == undefined) {
			console.log("消息类型为空");
			return
		}
		if (data.shootObjStates == 1) {
			this.m_createAllFrogs.frogCounterforce(data);
		}
		if (data.shootObjStates == 2) {

			this.m_createAllFrogs.frogFlick(data);
		}
	}
	private checkUserResurgence(userData): boolean {
		for (let i = 0; i < userData.length; i++) {
			if (userData[i].userId == DataProl.account && !userData[i].Death.isDeath) {
				return true;
			}
		}
		return false;
	}

	/**将玩家信息显示出来 */
	public displaMyInfo(player: any) {
		this.playerPanel.displayUserTongueLength(player.lineLength);
		var playertyp = player.frogType + 1 >= serverConfig.config.maxtype + 1 ? 0 : player.frogType + 1;
		this.playerPanel.displayUserClothesUpdata(playertyp);
	}

	private yaoganInit() {
		this.yaogan = new roleControl();
		this.UiLayer.addChild(this.yaogan);
		this.yaogan.yaoganInit(this.stage);
	}
	/**显示击杀效果 */
	public disPlayKillMan(num: number) {
		if (num > DataProl.killnumMax) {
			DataProl.killnumMax = num;
		}
		//console.log(DataProl.killnumMax + "最高连杀");
		this.playerPanel.frogKillMan(num);
		// SoundManager.getInstance().effectSound = null;
		if (num == 1) {
			SoundManager.getInstance().playEffectSound("firstblood_mp3");
		}
		else if (num == 2) {
			SoundManager.getInstance().playEffectSound("doublekill_mp3");
		}
		else if (num == 3) {
			SoundManager.getInstance().playEffectSound("triplekill_mp3");
		}
		else if (num == 4) {
			SoundManager.getInstance().playEffectSound("quatarykill_mp3");
		}
		else if (num == 5) {
			SoundManager.getInstance().playEffectSound("pentakill_mp3");
		}
		else if (num > 5 && num <= 10) {
			SoundManager.getInstance().playEffectSound("killingspree_mp3");
		}
		else if (num > 10 && num <= 20) {
			SoundManager.getInstance().playEffectSound("monsterkill_mp3");
		}
		else if (num > 20 && num <= 30) {
			SoundManager.getInstance().playEffectSound("godlike_mp3");
		}
		else if (num > 30) {
			SoundManager.getInstance().playEffectSound("legendary_mp3");
		}
	}

	// 发送给服务器玩家的位置
	public senMessageForServerPosition(point) {
		//道具醉酒
		if (this.myUser.userSprit.nowPropsType[3] == 4) {
			if (Date.now() - this.daotime >= 1000) {
				this.rr = Math.round(Math.random() * 360)
				this.daotime = Date.now();
			}
			point.x = Math.sin(this.rr / 57.3) * 815;
			point.y = Math.cos(this.rr / 57.3) * 815;
		}
		if (point.y == 0 && point.x == 0) {
			//console.log("发送位置为零");
			return;
		}
		var movedata = {
			"target": point,//gameMap.getInstance().canvas_Width,
			"account": DataProl.account,//gameMap.getInstance().canvas_Height
		}

		//12,这几个汉字的utf-8编码都占三个字节  
		//	console.log("发送玩家数据");
		//	webNetworkMananger.getInstance().SendMeesage('playerMove', movedata);


		let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
		let m_c2sPlayerMove = new awesomepackage.c2sPlayerMove();
		m_c2sPlayerMove.account = DataProl.account;
		// this.tmpPoint.x = point.x;
		// this.tmpPoint.y = point.y;
		// this.tmpPoint.normalize(1);
		// m_c2sPlayerMove.targetx = 	this.tmpPoint.x;
		// m_c2sPlayerMove.targety =	this.tmpPoint.y;
		//	let shadowFrog = this.m_createAllFrogs.findFrogById(DataProl.shadowFrogId);
		if (this.m_shadowFrog != null) {
			//	shadowFrog.isv
			m_c2sPlayerMove.x = this.m_shadowFrog.x;
			m_c2sPlayerMove.y = this.m_shadowFrog.y;
		}
		else {
			m_c2sPlayerMove.x = -1;
			m_c2sPlayerMove.y = -1;
		}
		m_c2sPlayerMove.targetx = point.x;
		m_c2sPlayerMove.targety = point.y;

		m_AwesomeMessage.meesageId = 1003;
		var buffer1 = awesomepackage.c2sPlayerMove.encode(m_c2sPlayerMove).finish();
		var deflate = new Zlib.Deflate(buffer1);
		var compressed = deflate.compress();
		m_AwesomeMessage.data = compressed;
		var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
		var byte2: egret.ByteArray = new egret.ByteArray(buffer);
		webNetworkMananger.getInstance().SendBitMeesage(byte2);
	}



	/**加载图片
	 * posx/posy 坐标
	 * rotate 旋转角度
	 * name 名字
	 * scale 大小
	 * isClear 是否可刷新
	 */
	private loadingImage(posx, posy, rotate, name, scale, isClear) {
		var loadimage: eui.Image = new eui.Image();
		loadimage.texture = RES.getRes(name);
		loadimage.x = posx;
		loadimage.y = posy;
		loadimage.rotation = rotate;
		loadimage.scaleX = scale;
		loadimage.scaleY = scale;
		isClear ? this.tongueLayer.addChild(loadimage) : this.addChild(loadimage);
	}

	//提交玩家自己的青蛙
	private creatMyFog() {
		this.m_createAllFrogs.getMyFrog(DataProl.account, DataProl.login_data.nickName, 550, 500, 0, 0, DataProl.userCurrentDressUp);

		this.myUser.targetx = this.myUser.userSprit.x;
		this.myUser.targety = this.myUser.userSprit.y;
	}
	/**返回大厅 */
	public backToHall() {
		this.game_Timer.removeEventListener(egret.TimerEvent.TIMER, this.game_Loop, this);
		this.game_Timer.reset();
		//添加层级处理
		this.removeUnusedLayer();
		SceneManager.instance.SitchScene(SceneName.登录场景);
		this.clearAll();//测试返回按钮时调用清空数据方法
		console.log("玩家返回大厅...");


	}
	public removeUnusedLayer() {
		if (this.UiLayer == null)
			return;

		if (this.playerPanel != null) {
			this.UiLayer.removeChild(this.playerPanel);
			this.playerPanel = null;
		}
		if (this.GameOver != null) {
			this.UiLayer.removeChild(this.GameOver);
			this.GameOver = null;
		}
		if (this.yaogan != null) {
			this.UiLayer.removeChild(this.yaogan);
			this.yaogan = null;
		}
		if (this.parent != null) {
			this.parent.removeChild(this.UiLayer);
			this.UiLayer = null;
		}

	}
	/**清空multGame数据 */
	public clearAll() {
		this.yaogan = null;
		this.camera = null;
		this.daotime = null;
		this.rr = null;
		this.background = null;
		this.clothes_List = null;
		this.myControlPoint = null;
		this.handle = null;
		this.circle = null;
		this.circle_position = null;
		this.handle_position = null;
		this.touchID = null;
		this.circle_radius = null;
		this.handle_radius = null;
		this.jiaodu = null;
		this.container = null;
		this.gameMapss = null;
		this.tmpPoint = null;
		this.bgSound = null;
		this.con = null;
		this.player = null;
		//this.myUser=null;//第一个注掉后，multGame里返回大厅方法backToHall可直接使用
		this.decoration_List = null;
		this.tongueLayer = null;
		this.propLayer = null;
		this.UiLayer = null;
		this.GameOver = null;
		//this.userDied = null;
		this.playerPanel = null;
		this.gameFrog = null;
		this.m_createAllFrogs = null;
		this.roomAllTongue = null;
		this.tongueManager = null;
		this.game_Timer = null;
		this.isUserDied = null;
		this.m_propMg = null;
		this.m_shadowFrog = null;
		this.game_Loop_tmp_point = null;
		webNetworkMananger.getInstance().gameSceneRec = null;
	}

}